const app = getApp();
import { orderInfo, getOrderReturnAddress, orderReturnAddExpress, orderApplyReturn, getReturnExpressList, orderReturnCancel, orderPreAuth, getRenewalGoodsStatus } from "../../../api/order";
import { getBtnsByStatus, cancelOrder, cancelRefundApply, confirmReceipt, payFirstRent } from "../../../utils/order";
import { disposeData } from "../../../utils/outData";
import { baseImgUrl } from "../../../setting";
import { createContract, orderInsuranceBuy, createAntchain } from "../../../api/index";
Page({
  data: {
    orderTip: '',
    order_id: '',
    goodsData: {},
    btns: [],
    showMore: false,
    showService: false,
    returnAddress: {},
    addressModal: false,
    addressBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '复制地址', extClass: 'button2' },
    ],
    addressOneBtn: [
      { text: '返回', extClass: 'button1' },
    ],
    returnModal: false,
    returnBtn: [
      { text: '取消', extClass: 'button1' },
      { text: '确认归还', extClass: 'button2' },
    ],
    returnApplyBtn: [
      { text: '取消申请', extClass: 'button1' },
      { text: '确认申请', extClass: 'button2' },
    ],
    order_id: '',
    status: 0,
    flowModal: false,
    flowList: [],
    flowIndex: -1,
    flowNo: '',
    placeholder: '请填写物流单号',
    disabledInput: false
  },
  closeService() {
    this.setData({
      showService: false
    })
  },
  onLoad(options) {
    this.setData({
      order_id: options.id || disposeData().id
    })
    this.getData();
  },
  goToBill(e) {
    const order_id = e.currentTarget.dataset.id;
    my.navigateTo({
      url: '../../../pagesA/pages/bill/bill?order_id=' + order_id + '&isView=' + true
    });
  },
  toSnapshot(e) {
    const { goodsId, orderId } = e.currentTarget.dataset
    my.navigateTo({
      url: '../../../pagesA/pages/orderSnapshot/orderSnapshot?goodsId=' + goodsId + '&orderId=' + orderId
    })
  },
  checkProtocol() {
    if (!this.data.goodsData || !this.data.goodsData.pact_url) {
      my.showToast({
        type: 'none',
        content: '还未签署协议',
        duration: 2000
      });
      return;
    }
    // my.showLoading({ content: '正在下载协议...' });
    console.log(this.data.goodsData.pact_url);
    my.downloadFile({
      url: baseImgUrl + this.data.goodsData.pact_url,
      success({ apFilePath }) {
        my.hideLoading();
        my.openDocument({
          filePath: apFilePath,
          fileType: 'pdf',
          success: (res) => {
            console.log('open document success')
          }
        })
      }
    })
  },
  checkOldOrder() {
    if (getCurrentPages().length === 5) {
      my.redirectTo({
        url: './orderpay?id=' + this.data.goodsData.parent_order_id
      });
    } else {
      my.navigateTo({
        url: './orderpay?id=' + this.data.goodsData.parent_order_id
      })
    }
  },
  checkReletOrder() {
    if (getCurrentPages().length === 5) {
      my.redirectTo({
        url: './orderpay?id=' + this.data.goodsData.sub_order_id
      });
    } else {
      my.navigateTo({
        url: './orderpay?id=' + this.data.goodsData.sub_order_id
      })
    }
  },
  getOrderTip(status) {
    switch (status) {
      case 4:
        this.setData({ orderTip: '审核发货预计要0.5-3个工作日，<span style="font-weight: bolder;font-size: 30rpx;">请您注意接听来电</span>' });
        break;
      case 2:
        this.setData({ orderTip: '预计两个小时后自动关闭订单，请及时处理' });
        break;
      case 10:
        this.setData({ orderTip: '审核发货预计需要3个工作日，<span style="font-weight: bolder;bolder;font-size: 30rpx;">请注意接听来电</span>' });
        break;
      case 11:
        this.setData({ orderTip: '审核退款预计1—3个工作日，<span style="font-weight: bolder;bolder;font-size: 30rpx;">请注意接听来电</span>' });
        break;
      case 20:
        this.setData({ orderTip: '您的订单已发货，请及时收货' });
        break;
      case 1:
        this.setData({ orderTip: '您的订单已取消' });
        break;
      case 60:
        this.setData({ orderTip: '您的订单已完成' });
        break;
      case 30:
        const { lease_time, month_total } = this.data.goodsData;
        const tip = '您的订单租期：' + lease_time + '（共' + month_total + '月）到期后请及时处理（归还、续租、买断）';
        this.setData({ orderTip: tip });
        break;
      case 13:
        this.setData({ orderTip: '商家拒绝退款，拒绝原因：' });
        break;
      case 16:
        const { setmeal_foregift, pay_type } = this.data.goodsData;
        this.setData({ orderTip: '您的订单已退款' + (pay_type == 2 ? '，已退回冻结押金￥' + setmeal_foregift : '') })
        break;
      case 41:
        this.setData({ orderTip: '您已申请归还，请主动联系商家进行处理，商家会在3个工作日内确认是否同意归还。' })
        break;
      case 42:
        this.setData({ orderTip: '商家已同意归还，请填写归还物流信息' })
        break;
      case 44:
        this.setData({ orderTip: '您已发货，等待商家收货' })
        break;
      case 45:
        this.setData({ orderTip: '商家已确认收货' })
        break;
      case 43:
        this.setData({ orderTip: '商家未同意归还，请联系商家' })
        break;
      case 62:
        const { buyout_amount } = this.data.goodsData;
        this.setData({ orderTip: '实付买断金额：￥' + buyout_amount });
        break;

      default:
        break;
    }
  },
  getData() {
    orderInfo(this.data.order_id).then(res => {
      my.stopPullDownRefresh();
      const btns = getBtnsByStatus(res).filter(item => {
        console.log(item,"item");
       return  item.id != 9
      });
      this.setData({
        goodsData: res || {},
        btns
      })
      this.getOrderTip(this.data.goodsData.status);
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  goToShop() {
    my.navigateTo({
      url: '../../storeDetails/storeDetails?member_id=' + this.data.goodsData.member_id
    });
  },
  copyOrderNum() {
    my.setClipboard({
      text: this.data.goodsData.trade_no,
      success: () => {
        my.alert({
          content: '已复制',
          buttonText: '我知道了'
        })
      }
    });
  },
  clickMore() {
    this.setData({
      showMore: !this.data.showMore
    })
  },
  setReason(e){
    const that = this;
    cancelOrder({order_id:this.data.order_id,name:e}, function () {
        that.getData();
        that.setData({
         showReasonPicker: false
       })
     })
 },
 closeReasonPicker() {
   this.setData({
     showReasonPicker: false
   })
 },
  btnClick(e) {
    console.log(e.currentTarget.dataset,"eee",this.data.btns);
    this.setData({
      showMore: false
    });
    const that = this;
    const { id, status, order_id, isAuth, pay_type, face_flow_id,esignUserId, flowId, sign_status, goods_id, contract_type, insurance_id } = e.currentTarget.dataset;
    this.setData({
      order_id,
      status
    })
    if ((id == 1 || id == 20) && (status == 3 && sign_status == 2)) {
   
      my.navigateTo({
        url: '../../../pagesA/pages/paymentPage/paymentPage?order_id=' + order_id
      })
    }
    if (id == 2) {
      this.setData({
        showReasonPicker: true,
      })
      const list = [
        {value: 7,name: '价格有点贵',checked: false},
        {value: 1,name: '商品拍错(机型/规格/颜色/套餐)',checked: false},
        {value: 2,name: '收货号码/地址填写错误',checked: false},
        {value: 3,name: '发货太慢了',checked: false},
        {value: 4,name: '没用/少用优惠',checked: false},
        {value: 5,name: '计划有变暂时不需要了',checked: false},
        {value: 6,name: '其他',checked: false},
    ];
      this.setData({reasonList:list});
      
    }
    if (id == 9) {
      my.navigateTo({
        url: '../../../pagesA/pages/applyRefund/applyRefund?order_id=' + order_id
      });
    }
    if (id == 18) {
      cancelRefundApply(order_id, function () {
        that.getData();
      })
    }
    if (id == 3 && status == 20) {
      confirmReceipt(order_id, function () {
        that.getData();
      })
    }
    if ((id == 6 && status == 44) || id == 19) {
      my.navigateTo({
        url: '../../../pagesA/pages/logistics/logistics?order_id=' + order_id
      });
    }
    if (id == 4) {
      my.navigateTo({
        url: '../../../pagesA/pages/bill/bill?order_id=' + order_id
      });
    }
    // if ((id == 1 || id == 20) && (status == 2 || sign_status != 2)) {
    if (id == 20){
      my.navigateTo({
        url: '../../authentications/authentications?orderId=' + order_id + '&payType=' + pay_type + '&isAuth=' + isAuth + '&esignUserId=' + esignUserId + '&flowId=' + flowId + '&face_flow_id='+face_flow_id+'&status=' + status + '&contractType=' + contract_type+ '&type=2'
      });
      // this.createContractMe(order_id, pay_type)
    }
    if ((id == 1 || id == 20) && (status == 3 && sign_status == 2)) {
      my.navigateTo({
        url: '../../../pagesA/pages/paymentPage/paymentPage?order_id=' + order_id
      })
    }
    if (id == 17) {
      this.setData({
        showService: true
      })
    }
    if (id == 7) {
      my.navigateTo({
        url: '../../../pagesA/pages/productDetails/productDetails?goodsId=' + goods_id+'&sale_user_id='+app.globalData.sale_user_id
      });
    }
    if (id == 14) {
      my.navigateTo({
        url: '../../../pagesA/pages/buyout/buyout?orderId=' + order_id
      });
    }
    // 立即归还
    if (id == 11) {
      if (status == 40) {
        this.setData({
          returnModal: true
        })
      } else if (status == 42) {
        getReturnExpressList().then(res => {
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      }
    }
    if(id=='99'){
      my.navigateTo({
        url: '../../../pages/authentication/authentication?orderId=' + order_id+'&contractType=2&&payType=1'
      })
    }
    // 获取归还地址
    if (id == 16) {
      getOrderReturnAddress(order_id).then(res => {
        if (res) {
          this.setData({
            returnAddress: res,
            addressModal: true
          })
        }
      }).catch(err => {
        this.setData({
          addressModal: false
        })
      })
    }
    // 取消归还
    if (id == 5) {
      orderReturnCancel(order_id).then(res => {
        my.showToast({
          type: 'none',
          content: '操作成功',
          duration: 1000,
        });
        that.getData();
      })
    }
    // 申请归还
    if (id == 10) {
      this.setData({
        returnModal: true
      })
    }
    // 再次申请
    if (id == 12) {
      orderApplyReturn(order_id).then(res => {
        that.getData();
      })
    }
    // 重新签约
    if (id == 22) {
      that.againPreAuth();
    }
    // 申请续租
    if (id == 15) {
      getRenewalGoodsStatus(order_id).then(res => {
        const { goods_id, setmeal_id, status } = res
        if (status == 1) {
          this.setData({
            reletModal: true,
            goodsStatus: status,
            goodsId: goods_id,
            setmealId: setmeal_id
          })
        } else {
          this.setData({
            reletModal: true,
            goodsStatus: '',
          })
        }
      }).catch(err => {
        this.setData({
          reletModal: false,
          goodsStatus: '',
        })
      })
    }
  },
  // 签约预授权
  againPreAuth() {
    const that = this
    orderPreAuth(that.data.order_id).then(res => {
      if (res.orderStr) {
        my.tradePay({
          orderStr: res.orderStr,
          success: (res) => {
            that.getData();
          },
          fail: (res) => {
            my.showToast({
              type: 'fail',
              content: '签约失败，请稍后重试',
              duration: 1000,
            });
          }
        });
      }
    })
  },
  onAddressClick(e) {
    let index = e.target.dataset.index
    if (index == 0) {
      this.setData({
        addressModal: false,
      });
    } else {
      my.setClipboard({
        text: this.data.returnAddress,
        success: () => {
          my.showToast({
            type: 'none',
            content: '复制成功',
            duration: 1000,
          });
        }
      });
    }
  },
  // 签署合同
  createContractMe(orderId, pay_type) {
    const env = 'prod'
    if (pay_type == 2) {
      const that = this
      createAntchain(orderId).then(res => {
        console.log('res', res)
        my.showLoading({ content: '正在跳转合同...' });
        function getSignUrl(aliSchema) {
          if (!aliSchema) { return '' }
          const querys = aliSchema.split('?')[1].split('&');
          const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
          const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
          return encodedSignUrl
        }
        const signUrl = getSignUrl(res.sign_url);
        my.navigateToMiniProgram({
          appId: '2021005103687601',
          path: `pages/signH5/index?signUrl=${signUrl}`,
          success: (res) => {
            // console.log(JSON.stringify(res))

            my.hideLoading({
              page: that,
            });
          },
          fail: (res) => {
            my.hideLoading({
              page: that,
            });
            // console.log(JSON.stringify(res))
          }
        });
      })
    } else if (pay_type == 1) {
      my.navigateTo({
        url: '../../../pagesA/pages/chainContract/chainContract?orderId=' + orderId
      })
    }

  },
  onReturnClick(e) {
    const that = this
    let index = e.target.dataset.index
    if (index == 0) {
      that.setData({
        returnModal: false,
      });
    } else {
      const { order_id, status } = that.data
      if (status == 40) {
        getReturnExpressList().then(res => {
          that.setData({
            returnModal: false,
            flowModal: true,
            flowList: res
          });
        })
      } else if (status == 30 || status == 39) {
        orderApplyReturn(order_id).then(res => {
          that.getData();
          that.setData({
            returnModal: false
          });
        })
      }
    }
  },
  bindPickerChange(e) {
    this.setData({
      flowIndex: e.detail.value,
      disabledInput: e.detail.value == 0 ? true : false,
      placeholder: e.detail.value == 0 ? '无需填写单号' : '请填写物流单号',
    });
  },
  onFlowNo(e) {
    let reg = /^[0-9A-Za-z]+$/
    if (!reg.test(e.detail.value)) {
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
    }
    this.setData({ flowNo: e.detail.value })
  },
  toAddFlow() {
    const that = this
    const { order_id, flowIndex, flowNo, flowList } = that.data
    const reg = /^[0-9A-Za-z]+$/
    if (flowIndex < 0) {
      my.showToast({
        type: 'none',
        content: '请选择物流名称',
        duration: 1500,
      });
      return false
    }
    if (!flowNo && flowIndex > 0) {
      my.showToast({
        type: 'none',
        content: '请填写物流单号',
        duration: 1500,
      });
      return false
    }
    if (flowNo && !reg.test(flowNo)) {
      my.showToast({
        type: 'none',
        content: '请填写正确的物流单号',
        duration: 1500,
      });
      return false
    }
    orderReturnAddExpress({
      order_id,
      logistics_name: flowList[flowIndex].name,
      logistics_no: flowNo,
    }).then(res => {
      this.setData({
        flowModal: false
      });
      that.getData();
    })
  },
  closeModal() {
    this.setData({
      flowModal: false
    })
  },
  onPullDownRefresh() {
    this.getData();
  }
});
